package com.x.erp.dao;

import com.x.erp.model.CarSale;
import com.x.framework.dao.BaseDao;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

/**
 * 销售出库DAO
 */
@Repository
public class CarSaleDao extends BaseDao {

	private final static String selectSaleListSql = "SELECT " +
			"ecs.*, " +
			"eu.USER_NAME, " +
			"bp.PROVINCE_NAME, " +
			"bc.CITY_NAME " +
			"FROM " +
			"ERP_CAR_SALE ecs  " +
			"JOIN ERP_USER eu ON ecs.SALE_DEAL_USER_ID = eu.USER_ID " +
			"LEFT JOIN BASE_PROVINCE bp ON ecs.PROVINCE_ID = bp.PROVINCE_ID " +
			"LEFT JOIN BASE_CITY bc ON ecs.CITY_ID = bc.CITY_ID " +
			"WHERE 1=1 ";
	/**
	 * 查询销售出库列表
	 * @param carSale
	 * @return
	 * @throws Exception
	 */
	public List<CarSale> selectCarSaleList(CarSale carSale) throws Exception{
		StringBuilder sql = new StringBuilder(selectSaleListSql);
		List<Object> params = new ArrayList<Object>();
		searchCondition(sql, params, carSale);
		return this.queryForList(sql.toString(), CarSale.class, params);
	}

	private final static String selectSaleNumSql = "SELECT COUNT(ecs.SALE_ID) FROM ERP_CAR_SALE ecs WHERE true ";
	/**
	 * 查询销售出库数量
	 * @param carSale
	 * @return
	 * @throws Exception
	 */
	public int selectCarSaleNum(CarSale carSale) throws Exception{
		StringBuilder sql = new StringBuilder(selectSaleNumSql);
		List<Object> params = new ArrayList<Object>();
		searchCondition(sql, params, carSale);
		return this.queryForInt(sql.toString(), params);
	}

	/**
	 * 查询条件
	 * @param sql
	 * @param params
	 * @param carSale
	 */
	private void searchCondition(StringBuilder sql, List<Object> params, CarSale carSale) {
		if(carSale != null) {
			if(StringUtils.isNotEmpty(carSale.getSaleId())){
				sql.append("AND ecs.SALE_ID = ? ");
				params.add(carSale.getSaleId());
			}
			if(StringUtils.isNotEmpty(carSale.getCarId())){
				sql.append("AND ecs.CAR_ID = ? ");
				params.add(carSale.getCarId());
			}
		}
	}
}
